﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.Entity;
using System.Data;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.Data;

public class FormAuthorization
{

    public LoginResult Authorization(LoginUser account, HttpContext Context)
    {
        var user = new UserManager().GetUserByCode(account.UserName);

        SystemConfigManager configManager = new SystemConfigManager();
        LoginResult result = null;

        //获取版本号
        result = new LoginResult();
        result.EmployeeID = null;
        if (user != null) //存在该用户
        {
            #region 存在该用户的判断

            result.EmployeeID = null;
            if (account.UserPwd.Equals(user.PASSWORD))
            {
                result.LoginSuccessful = true;
                if ("1".Equals(user.ISLOCK))
                {
                    //记录帐号被锁定信息
                    EventManager.CreateNewEvent(LogType.LOGIN_USERLOCKEDOUT, account.UserName, user.ID, string.Format("用户{0}帐号被锁定,IP:{1},主机名:{2}", user.CODE, Context.Request.UserHostAddress, Context.Request.UserHostName));

                    result.IsLock = true;
                }
                else
                {
                    //判断是否开启设备捆绑验证
                    //SystemConfig configEnableBoundDevice = configManager.Load(ConfigType.EnableBoundDevice,user.DOMAINID);
                    int res = Jumpton.SFA.Server.BusinessRule.UserDeviceBoundManager.CheckUserDevice(account.IMEICode, int.Parse(user.DOMAINID.ToString()), user.ID.ToString());
                    if (res != -1 && res != -3 && res != -4)
                    {
                        user.FAILLOGINCOUNT = "0";
                        result.EmployeeID = user.PERSONID.ToString();
                        //记录登录成功信息
                        EventManager.CreateNewEvent(LogType.LOGIN_SUCCESS, account.UserName, user.ID, string.Format("用户{0}登录成功,IP:{1},主机名:{2}", account.UserName, Context.Request.UserHostAddress, Context.Request.UserHostName));
                    }
                    else
                    {
                        result.LoginSuccessful = false;
                        result.DeviceUnAuthorization = true;
                        string message = "";
                        if (res == -1) message = "该设备已被禁止使用";
                        if (res == -3) message = String.Format("该设备与{0}帐号绑定失效，无权登录", user.CODE);
                        if (res == -4) message = String.Format("不能在该设备上使用{0}帐号登录", user.CODE);
                        result.Message = message;
                        //记录登录失败日志
                        EventManager.CreateNewEvent(LogType.LOGIN_FAILURE, account.UserName, "-1", string.Format("用户{0}设备未通过验证,IP:{1},主机名:{2},IMEI={3}", account.UserName, Context.Request.UserHostAddress, Context.Request.UserHostName, account.IMEICode));
                        return result;

                    }



                    //user.FAILLOGINCOUNT = "0";
                    result.DomainID = user.DOMAINID.ToString();
                    result.UserID = user.ID.ToString();
                    result.PERSON_ID = user.PERSONID.ToString();
                    result.UserCode = user.CODE;
                    result.UserName = user.PERSON.Name;
                    result.EmployeeID = user.PERSONID.ToString();
                    result.UserToken = user.UserToken;
                    var person = new Jumpton.SFA.Server.BusinessRule.MasterData.PersonManager().Load(user.PERSONID);
                    if (person != null)
                    {
                        result.Organization = person.OrgID.ToString();
                        result.EmployeeCode = person.Code;
                    }

                    //记录登录成功信息
                    EventManager.CreateNewEvent(LogType.LOGIN_SUCCESS, user.CODE, user.ID, string.Format("用户{0}登录成功,IP:{1},主机名:{2}", user.CODE, Context.Request.UserHostAddress, Context.Request.UserHostName));
                    result.SessionId = Guid.NewGuid().ToString();
                    result.ServerUrl = Context.Request.ApplicationPath;

                    //获取该用户的权限
                    var ot = new Jumpton.SFA.Server.BusinessRule.System.RoleManager().GetUserRole(user.ID, 1);
                    Module[] MODULES = new Module[ot.Rows.Count];
                    int i = 0;
                    String URL = Context.Request.Url.ToString().ToUpper();
                    try
                    {
                        URL = URL.Substring(0, URL.LastIndexOf(Context.Request.ApplicationPath.ToUpper())) + Context.Request.ApplicationPath + "/IMAGES/{0}";
                    }
                    catch
                    {
                        // URL = Context.Request.ApplicationPath;
                    }
                    foreach (DataRow row in ot.Rows)
                    {
                        Module module = new Module();
                        module.ID = ot.Rows[i]["MODULE_ITEM_ID"].ToString();
                        module.NAME = ot.Rows[i]["ITEM_NAME"].ToString();
                        module.Key = ot.Rows[i]["ITEM_LINK"].ToString();
                        module.ImageResource = String.Format(URL, ot.Rows[i]["SMALL"].ToString());
                        module.Page = ot.Rows[i]["PAGE_INDEX"].ToString();
                        String Source = ot.Rows[i]["SOURCE"].ToString();
                        if (!(Source.ToUpper().IndexOf("HTTP") == 0))
                        {
                            module.RSSSource = QueryStringHelper.GetRootURI(Context) + "/" + ot.Rows[i]["SOURCE"].ToString();
                        }
                        else
                        {
                            module.RSSSource = ot.Rows[i]["SOURCE"].ToString();
                        }
                        module.Type = ot.Rows[i]["SOURCETYPE"].ToString();
                        //module.RSSSource = ot.Rows[i]["rss_source"].ToString();
                        MODULES[i++] = module;
                    }
                    result.ValuesList = MODULES;



                    //记录会话信息
                    new SessionManager().SaveSession(result.SessionId, DateTime.Now, user.ID.ToString());
                }
            }
            #endregion
            else
            {
                result.LoginSuccessful = false;
                user.FAILLOGINCOUNT = (int.Parse(user.FAILLOGINCOUNT) + 1).ToString();
                //记录登录失败日志
                EventManager.CreateNewEvent(LogType.LOGIN_FAILURE, account.UserName, "", string.Format("用户{0}登录失败,IP:{1},主机名:{2}", account.UserName, Context.Request.UserHostAddress, Context.Request.UserHostName));
                result.Message = "用户账号、密码不匹配,登录失败";
                //获取连续登录失败次数是否被锁定
                SystemConfig config = configManager.Load(ConfigType.SeriesFailLoginCount, user.DOMAINID);
                try
                {
                    //超过次数则自动锁定该帐号
                    if (config != null && int.Parse(user.FAILLOGINCOUNT) >= int.Parse(config.Value))
                    {
                        user.ISLOCK = true;
                        result.IsLock = true;

                    }
                }
                catch
                {

                }

            }
            user.Save();

            ////判断是否需要设置需要修改密码
            //Jumpton.FSA.Entity.SystemConfig LoginNeedToChangePassword = configManager.Load(Jumpton.FSA.Entity.ConfigType.LoginNeedToChangePassword);
            //if (LoginNeedToChangePassword != null && LoginNeedToChangePassword.Value.Equals("1") && user.PASSWORDCHANGED != "1")
            //    result.NeedToChangePassword = true;
            //保存回话信息

        }
        else
        {
            result.LoginSuccessful = false;
            result.Message = "用户账号、密码不匹配";
        }


        return result;
    }



}

